/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ConsultoresDialog.java
 *
 * Created on Oct 22, 2010, 11:06:21 AM
 */
package br.com.tbp.gui;

import br.com.tbp.controle.ControleEmpresa;
import br.com.tbp.controle.ControlePedido;
import br.com.tbp.exception.PersistenciaException;
import br.com.tbp.gui.paging.ListPaginator;
import br.com.tbp.gui.table.EmpresasTableModel;
import br.com.tbp.gui.table.JTableUtils;
import br.com.tbp.model.domain.Empresa;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JComponent;
import javax.swing.JOptionPane;
import javax.swing.JRootPane;
import javax.swing.KeyStroke;
import javax.swing.text.MaskFormatter;

/**
 *
 * @author Diego Freire
 */
public class EmpresasPaginadaDialog extends javax.swing.JDialog {

    private Empresa empresa;
    private boolean select = false;
    private EmpresasTableModel model;
    private ControleEmpresa controle = new ControleEmpresa();
    private MenuPrincipal menu;
    private String cnpjMask = "##.###.###/####-##";
    private MaskFormatter maskFormatter;
    private ListPaginator<Empresa> data;
    private final int PAGE_SIZE = 30;

    public EmpresasPaginadaDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        if (parent instanceof MenuPrincipal) {
            this.menu = (MenuPrincipal) parent;
        }
        setLocationRelativeTo(null);
    }

    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        contentPanel = new javax.swing.JPanel();
        split1 = new javax.swing.JSplitPane();
        buscaPanel = new javax.swing.JPanel();
        radio1 = new javax.swing.JRadioButton();
        radio2 = new javax.swing.JRadioButton();
        radio3 = new javax.swing.JRadioButton();
        radio4 = new javax.swing.JRadioButton();
        jLabel1 = new javax.swing.JLabel();
        inputTextField = new javax.swing.JFormattedTextField();
        okButton = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jPanel6 = new javax.swing.JPanel();
        scrollpane = new javax.swing.JScrollPane();
        tabela = new javax.swing.JTable();
        jPanel3 = new javax.swing.JPanel();
        jPanel4 = new javax.swing.JPanel();
        listarButton = new javax.swing.JButton();
        cadastrarButton = new javax.swing.JButton();
        jPanel5 = new javax.swing.JPanel();
        msgLabel = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        jPanel7 = new javax.swing.JPanel();
        removerButton = new javax.swing.JButton();
        selecionarServicoButton = new javax.swing.JButton();
        fecharButton = new javax.swing.JButton();
        pagingPanel = new javax.swing.JPanel();
        primeiroButton = new javax.swing.JButton();
        anteriorButton = new javax.swing.JButton();
        pageLabel = new javax.swing.JLabel();
        proximoButton = new javax.swing.JButton();
        ultimoButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("TBP - Empresas");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        contentPanel.setLayout(new java.awt.BorderLayout());

        buttonGroup1.add(radio1);
        radio1.setSelected(true);
        radio1.setText("Nome fantasia");
        radio1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                radio1ActionPerformed(evt);
            }
        });

        buttonGroup1.add(radio2);
        radio2.setText("ID empresa");
        radio2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                radio2ActionPerformed(evt);
            }
        });

        buttonGroup1.add(radio3);
        radio3.setText("Razão social");
        radio3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                radio3ActionPerformed(evt);
            }
        });

        buttonGroup1.add(radio4);
        radio4.setText("CNPJ");
        radio4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                radio4ActionPerformed(evt);
            }
        });

        jLabel1.setText("Busca simples");

        inputTextField.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 5, 1, 1));
        inputTextField.setToolTipText("Selecione o filtro abaixo e digite para buscar");
        inputTextField.setFocusLostBehavior(javax.swing.JFormattedTextField.PERSIST);
        inputTextField.setFont(new java.awt.Font("Dialog", 0, 15));
        inputTextField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                inputTextFieldActionPerformed(evt);
            }
        });

        okButton.setText("OK");
        okButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                okButtonActionPerformed(evt);
            }
        });

        jLabel2.setText("> Selecione o filtro abaixo e digite para buscar");

        javax.swing.GroupLayout buscaPanelLayout = new javax.swing.GroupLayout(buscaPanel);
        buscaPanel.setLayout(buscaPanelLayout);
        buscaPanelLayout.setHorizontalGroup(
            buscaPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(buscaPanelLayout.createSequentialGroup()
                .addGroup(buscaPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(buscaPanelLayout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addComponent(radio1, javax.swing.GroupLayout.DEFAULT_SIZE, 256, Short.MAX_VALUE))
                    .addGroup(buscaPanelLayout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addGroup(buscaPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(radio2)
                            .addComponent(radio3, javax.swing.GroupLayout.DEFAULT_SIZE, 256, Short.MAX_VALUE)))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, buscaPanelLayout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addComponent(radio4, javax.swing.GroupLayout.DEFAULT_SIZE, 256, Short.MAX_VALUE))
                    .addGroup(buscaPanelLayout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(buscaPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addGroup(buscaPanelLayout.createSequentialGroup()
                                .addComponent(inputTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 199, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(okButton))
                            .addComponent(jLabel2))))
                .addContainerGap())
        );
        buscaPanelLayout.setVerticalGroup(
            buscaPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(buscaPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(buscaPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(inputTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(okButton, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(4, 4, 4)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(radio1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(radio3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(radio4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(radio2)
                .addContainerGap(191, Short.MAX_VALUE))
        );

        split1.setLeftComponent(buscaPanel);

        jPanel6.setLayout(new java.awt.BorderLayout());

        scrollpane.setPreferredSize(new java.awt.Dimension(750, 500));

        tabela.setFont(new java.awt.Font("Dialog", 0, 13));
        tabela.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {},
                {},
                {}
            },
            new String [] {

            }
        ));
        tabela.setRowHeight(22);
        tabela.setRowSelectionAllowed(false);
        tabela.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        tabela.setShowHorizontalLines(false);
        tabela.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tabelaMouseClicked(evt);
            }
        });
        scrollpane.setViewportView(tabela);

        jPanel6.add(scrollpane, java.awt.BorderLayout.CENTER);

        jPanel3.setBackground(new java.awt.Color(255, 255, 255));
        jPanel3.setLayout(new java.awt.BorderLayout());

        jPanel4.setBackground(new java.awt.Color(255, 255, 255));

        listarButton.setBackground(new java.awt.Color(150, 184, 250));
        listarButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/tbp/resources/listar16.png"))); // NOI18N
        listarButton.setText("Listar Todas");
        listarButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                listarButtonActionPerformed(evt);
            }
        });
        jPanel4.add(listarButton);

        cadastrarButton.setBackground(new java.awt.Color(150, 184, 250));
        cadastrarButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/tbp/resources/clientes16.png"))); // NOI18N
        cadastrarButton.setText("Nova Empresa");
        cadastrarButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cadastrarButtonActionPerformed(evt);
            }
        });
        jPanel4.add(cadastrarButton);

        jPanel3.add(jPanel4, java.awt.BorderLayout.LINE_END);

        jPanel5.setBackground(new java.awt.Color(255, 255, 255));
        jPanel5.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 4, 1, 1));
        jPanel5.setLayout(new java.awt.BorderLayout());

        msgLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/tbp/resources/customers32.png"))); // NOI18N
        msgLabel.setText("mensagem");
        msgLabel.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jPanel5.add(msgLabel, java.awt.BorderLayout.PAGE_END);

        jPanel3.add(jPanel5, java.awt.BorderLayout.LINE_START);

        jPanel6.add(jPanel3, java.awt.BorderLayout.PAGE_START);

        jPanel1.setLayout(new java.awt.BorderLayout());

        jPanel7.setBackground(new java.awt.Color(255, 255, 255));
        jPanel7.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.RIGHT));

        removerButton.setBackground(new java.awt.Color(150, 184, 250));
        removerButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/tbp/resources/trash.png"))); // NOI18N
        removerButton.setText("Remover Empresa");
        removerButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                removerButtonActionPerformed(evt);
            }
        });
        jPanel7.add(removerButton);

        selecionarServicoButton.setBackground(new java.awt.Color(150, 184, 250));
        selecionarServicoButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/tbp/resources/cursor16.png"))); // NOI18N
        selecionarServicoButton.setText("Selecionar Empresa");
        selecionarServicoButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                selecionarServicoButtonActionPerformed(evt);
            }
        });
        jPanel7.add(selecionarServicoButton);

        fecharButton.setBackground(new java.awt.Color(150, 184, 250));
        fecharButton.setText("Fechar (ESC)");
        fecharButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                fecharButtonActionPerformed(evt);
            }
        });
        jPanel7.add(fecharButton);

        jPanel1.add(jPanel7, java.awt.BorderLayout.PAGE_END);

        pagingPanel.setBackground(new java.awt.Color(235, 224, 224));
        pagingPanel.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        primeiroButton.setBackground(new java.awt.Color(255, 255, 153));
        primeiroButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/tbp/resources/first.png"))); // NOI18N
        primeiroButton.setToolTipText("Primeiro");
        primeiroButton.setPreferredSize(new java.awt.Dimension(70, 26));
        primeiroButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                primeiroButtonActionPerformed(evt);
            }
        });
        pagingPanel.add(primeiroButton);

        anteriorButton.setBackground(new java.awt.Color(255, 255, 153));
        anteriorButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/tbp/resources/prev.png"))); // NOI18N
        anteriorButton.setToolTipText("Anterior");
        anteriorButton.setPreferredSize(new java.awt.Dimension(70, 26));
        anteriorButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                anteriorButtonActionPerformed(evt);
            }
        });
        pagingPanel.add(anteriorButton);

        pageLabel.setFont(new java.awt.Font("Dialog", 1, 13));
        pageLabel.setText("páginas");
        pagingPanel.add(pageLabel);

        proximoButton.setBackground(new java.awt.Color(255, 255, 153));
        proximoButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/tbp/resources/next.png"))); // NOI18N
        proximoButton.setToolTipText("Próximo");
        proximoButton.setPreferredSize(new java.awt.Dimension(70, 26));
        proximoButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                proximoButtonActionPerformed(evt);
            }
        });
        pagingPanel.add(proximoButton);

        ultimoButton.setBackground(new java.awt.Color(255, 255, 153));
        ultimoButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/tbp/resources/last.png"))); // NOI18N
        ultimoButton.setToolTipText("Último");
        ultimoButton.setPreferredSize(new java.awt.Dimension(70, 26));
        ultimoButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ultimoButtonActionPerformed(evt);
            }
        });
        pagingPanel.add(ultimoButton);

        jPanel1.add(pagingPanel, java.awt.BorderLayout.CENTER);

        jPanel6.add(jPanel1, java.awt.BorderLayout.PAGE_END);

        split1.setRightComponent(jPanel6);

        contentPanel.add(split1, java.awt.BorderLayout.CENTER);

        getContentPane().add(contentPanel, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void tabelaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tabelaMouseClicked
        if (evt.getClickCount() == 2) {
            selecionarEmpresa(tabela.getSelectedRow());
        }
}//GEN-LAST:event_tabelaMouseClicked

    private void selecionarServicoButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_selecionarServicoButtonActionPerformed
        selecionarEmpresa(tabela.getSelectedRow());
}//GEN-LAST:event_selecionarServicoButtonActionPerformed

    private void fecharButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fecharButtonActionPerformed
        dispose();
    }//GEN-LAST:event_fecharButtonActionPerformed

    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
        try {
            this.refreshUltimosCadastrados(controle.pesquisar(0, 20));
        } catch (PersistenciaException pex) {
            System.out.println(pex.getMessage());
        }
    }//GEN-LAST:event_formWindowOpened

    private void radio1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_radio1ActionPerformed
        instalaCnpjMask(false);
        inputTextField.requestFocus();
        inputTextField.selectAll();
    }//GEN-LAST:event_radio1ActionPerformed

    private void radio2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_radio2ActionPerformed
        instalaCnpjMask(false);
        inputTextField.requestFocus();
        inputTextField.selectAll();
    }//GEN-LAST:event_radio2ActionPerformed

    private void radio3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_radio3ActionPerformed
        instalaCnpjMask(false);
        inputTextField.requestFocus();
        inputTextField.selectAll();
    }//GEN-LAST:event_radio3ActionPerformed

    private void radio4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_radio4ActionPerformed
        instalaCnpjMask(true);
        inputTextField.requestFocus();
        inputTextField.selectAll();
    }//GEN-LAST:event_radio4ActionPerformed

    private void cadastrarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cadastrarButtonActionPerformed
        EmpresaDialog dialog = new EmpresaDialog(this.menu, "TBP - Empresa", true);
        dialog.setEmpresa(new Empresa());
        dialog.setNovaEmpresa(true);
        dialog.setVisible(true);
    }//GEN-LAST:event_cadastrarButtonActionPerformed

    private void listarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_listarButtonActionPerformed
        try {
            this.refresh(controle.pesquisar());
        } catch (PersistenciaException pex) {
            System.out.println(pex.getMessage());
        }
    }//GEN-LAST:event_listarButtonActionPerformed

    private void removerButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removerButtonActionPerformed
        int row = tabela.getSelectedRow();
        if (row >= 0) {
            Empresa e = model.getEmpresa(row);
            if (e != null) {
                Object[] opcoes = {"Sim", "Não"};
                int resposta = JOptionPane.showOptionDialog(this,
                        "Confirma remover a empresa " + e.getNomeFantasia() + " ?",
                        "Atenção", JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE,
                        null, opcoes, opcoes[1]);
                if (resposta == 0) {
                    try {
                        controle.remover(e);

                        ControlePedido controle_pedido = new ControlePedido();
                        controle_pedido.removerPedidoPelaEmpresa(e);

                        model.removeEmpresa(e);
                        JOptionPane.showMessageDialog(null, "A empresa " + e.getNomeFantasia() + " foi removida com sucesso.",
                                "Informação", JOptionPane.INFORMATION_MESSAGE);
                    } catch (PersistenciaException pex) {
                        System.out.println(pex.getMessage());
                    }
                }
            }
        }
    }//GEN-LAST:event_removerButtonActionPerformed

    private void proximoButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_proximoButtonActionPerformed
        proximoResultado();
    }//GEN-LAST:event_proximoButtonActionPerformed

    private void primeiroButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_primeiroButtonActionPerformed
        primeiroResultado();
    }//GEN-LAST:event_primeiroButtonActionPerformed

    private void anteriorButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_anteriorButtonActionPerformed
        anteriorResultado();
    }//GEN-LAST:event_anteriorButtonActionPerformed

    private void ultimoButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ultimoButtonActionPerformed
        ultimoResultado();
    }//GEN-LAST:event_ultimoButtonActionPerformed

    private void inputTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_inputTextFieldActionPerformed
        buscaEmpresa(inputTextField.getText());
}//GEN-LAST:event_inputTextFieldActionPerformed

    private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed
        buscaEmpresa(inputTextField.getText());
}//GEN-LAST:event_okButtonActionPerformed

    private void refresh(Empresa e) {
        List<Empresa> lista = new ArrayList<Empresa>();
        if (e != null) {
            lista.add(e);
        }
        refresh(lista);
    }

    private void refreshUltimosCadastrados(List<Empresa> lista) {
        model = new EmpresasTableModel(lista);
        tabela.setModel(model);

        pagingPanel.setVisible(false);

        if (lista.isEmpty()) {
            msgLabel.setText("Não há nenhuma empresa cadastrada");
        } else if (model.getRowCount() == 1) {
            msgLabel.setText("Exibindo última empresa cadastrada");
        } else {
            int size = lista.size();
            msgLabel.setText("Exibindo últimas " + size + " empresas cadastradas");
        }
        JTableUtils.fitAllColumns(tabela);
        inputTextField.requestFocus();
        inputTextField.selectAll();
    }

    private void refresh(List<Empresa> lista) {
        model = new EmpresasTableModel();
        data = new ListPaginator<Empresa>(lista, PAGE_SIZE);
        model.setData(data.nextResult());
        tabela.setModel(model);

        atualizaPaginacao();
        if(!pagingPanel.isVisible()) {
            pagingPanel.setVisible(true);
        }
        if (lista.isEmpty()) {
            msgLabel.setText("Não há nenhuma empresa cadastrada");
        } else {
            int count = model.getRowCount();
            msgLabel.setText("Exibindo " + count + " empresas cadastradas");
        }
        JTableUtils.fitAllColumns(tabela);
        inputTextField.requestFocus();
        inputTextField.selectAll();
    }
    // <editor-fold defaultstate="collapsed" desc="Declaration of class members">
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton anteriorButton;
    private javax.swing.JPanel buscaPanel;
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JButton cadastrarButton;
    private javax.swing.JPanel contentPanel;
    private javax.swing.JButton fecharButton;
    private javax.swing.JFormattedTextField inputTextField;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JPanel jPanel6;
    private javax.swing.JPanel jPanel7;
    private javax.swing.JButton listarButton;
    private javax.swing.JLabel msgLabel;
    private javax.swing.JButton okButton;
    private javax.swing.JLabel pageLabel;
    private javax.swing.JPanel pagingPanel;
    private javax.swing.JButton primeiroButton;
    private javax.swing.JButton proximoButton;
    private javax.swing.JRadioButton radio1;
    private javax.swing.JRadioButton radio2;
    private javax.swing.JRadioButton radio3;
    private javax.swing.JRadioButton radio4;
    private javax.swing.JButton removerButton;
    private javax.swing.JScrollPane scrollpane;
    private javax.swing.JButton selecionarServicoButton;
    private javax.swing.JSplitPane split1;
    private javax.swing.JTable tabela;
    private javax.swing.JButton ultimoButton;
    // End of variables declaration//GEN-END:variables

    // </editor-fold>
    public EmpresasTableModel getModel() {
        return model;
    }

    @Override
    protected JRootPane createRootPane() {
        ActionListener closeListener = new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                fecharButtonActionPerformed(e);
            }
        };
        KeyStroke stroke =
                KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
        JRootPane myRootPane = new JRootPane();
        myRootPane.registerKeyboardAction(
                closeListener, stroke, JComponent.WHEN_IN_FOCUSED_WINDOW);

        return myRootPane;
    }

    public Empresa getEmpresa() {
        return empresa;
    }

    public void setEmpresa(Empresa e) {
        this.empresa = e;
    }

    public boolean isSelect() {
        return select;
    }

    public void setSelect(boolean select) {
        this.select = select;
    }

    private void selecionarEmpresa(int row) {
        if (row >= 0) {
            Empresa e = model.getEmpresa(row);
            if (e != null) {
                if (!isSelect()) {
                    EmpresaDialog dialog = new EmpresaDialog(this.menu, "TPB - Empresa", true);
                    dialog.setEmpresa(e);
                    dialog.setNovaEmpresa(false);
                    dialog.setVisible(true);
                } else {
                    setEmpresa(e);
                    dispose();
                }
            }
        }
    }

    private void buscaEmpresa(String texto) {
        if ((texto == null) || (texto.isEmpty())) {
            refresh(new ArrayList<Empresa>());
        } else {
            try {
                if (radio1.isSelected()) {
                    refresh(controle.pesquisarPorNomeFantasia(texto));
                } else if (radio3.isSelected()) {
                    refresh(controle.pesquisarPorRazaoSocial(texto));
                } else if (radio4.isSelected()) {
                    refresh(controle.pesquisarPorCnpj(texto));
                } else if (radio2.isSelected()) {
                    try {
                        long id = Long.parseLong(texto);
                        refresh(controle.pesquisarPorId(id));
                    } catch (NumberFormatException nfe) {
                        refresh(new ArrayList<Empresa>());
                    }
                }
            } catch (PersistenciaException pex) {
                System.out.println(pex.getMessage());
            }
        }
    }

    private void instalaCnpjMask(boolean instalar) {
        if (maskFormatter == null) {
            try {
                maskFormatter = new MaskFormatter(cnpjMask);
            } catch (ParseException pex) {
            }
        }
        if (instalar) {
            maskFormatter.install(inputTextField);
        } else {
            maskFormatter.uninstall();
        }
    }

    public static void main(String[] args) {
        EmpresasPaginadaDialog dialog = new EmpresasPaginadaDialog(null, true);
        dialog.setVisible(true);
    }

    private void proximoResultado() {
        try {
            if (data.getCurrentPage() >= data.getMaxPage()) {
                data.setCurrentPage(data.getMaxPage());
            }
            model.setData(data.nextResult());
            atualizaPaginacao();
        } catch (Exception e) {
            return;
        }
    }

    private void primeiroResultado() {
        data.setCurrentPage(0);
        model.setData(data.nextResult());
        atualizaPaginacao();
    }

    private void anteriorResultado() {
        if (data.getCurrentPage() - 2 < 0) {
            return;
        } else {
            data.setCurrentPage(data.getCurrentPage() - 2);
            model.setData(data.nextResult());
            atualizaPaginacao();
            return;
        }
    }

    private void ultimoResultado() {
        data.setCurrentPage(data.getMaxPage());
        model.setData(data.nextResult());
        atualizaPaginacao();
    }

    private void atualizaPaginacao() {
        pageLabel.setText((new StringBuilder("Página ").append(String.valueOf(data.getCurrentPage()))).append(" de ").append(
                data.getMaxPage() + 1).toString());
        msgLabel.setText("Exibindo " + model.getRowCount() + " empresas cadastradas");
    }
}
